package demo2;

//求链表的公共节点

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int len1 = getLen(pHead1);
        int len2 = getLen(pHead2);
        if(len1 < len2) {
            ListNode t = pHead1;
            pHead1 = pHead2;
            pHead2 = t;
        }
        int k = Math.abs(len1-len2);
        ListNode cur = pHead1;
        while(k-->0) {
            cur = cur.next;
        }
        while(cur!=null && pHead2!=null) {
            if(cur.val == pHead2.val) {
                return cur;
            }
            cur = cur.next;
            pHead2 = pHead2.next;
        }
        return null;
    }
    public int getLen(ListNode head) {
        int len = 0;
        ListNode cur = head;
        while(cur!=null) {
            cur = cur.next;
            len++;
        }
        return len;
    }
}
